<template>
  <div class="listDetailSp">
    <div v-if="isSp === '1'" class="header">
      <div class="cell">
        <div>
          启用时间范围
        </div>
        <u-switch v-model="isOpenTimeRange" @change="timeStatucChange" />
      </div>

      <transition
        enter-active-class="animate__animated animate__slideInLeft speedTimePickOut"
        leave-active-class="animate__animated animate__slideOutLeft speedTimePickOut"
      >
        <div v-show="isOpenTimeRange" class="cell" @click="timePickvisible = true">
          <div>
            <span style="color: red;margin-right: 5px;">*</span>时间
          </div>

          <div class="cell-right">
            <span>{{ pickerValue.length ? pickerValue.join('-') : '请选择' }}</span>
            <u-icon size="40" color="#E5E5E5" name="arrow-right" />
          </div>
        </div>
      </transition>

      <W-Picker
        ref="range"
        :visible.sync="timePickvisible"
        mode="range"
        fields="month"
        :value="pickerValue"
        :current="true"
        :range-type="'date'"
        theme-color="#007aff"
        @confirm="pickTimer"
      />
    </div>

    <div class="listDetailSp_container">
      <div class="usrs_header">
        <u-checkbox
          v-model="toggleSelect"
          :icon-size="30"
          :size="40"
          @change="checkboxAll"
        >
          全选
        </u-checkbox>
        <u-input
          v-model="searchUser"
          size="mini"
          placeholder="搜索接收人员"
          :type="'text'"
          :style="{
            'background-color': '#fff',
            'bottom': '5px'
          }"
          border
        />
      </div>
      <div class="userSelect_container">
        <u-checkbox-group
          wrap
          :icon-size="30"
          :size="40"
          @change="checkboxGroupChange"
        >
          <u-checkbox
            v-for="(item, index) in filteredUser"
            :key="index"
            v-model="item.myChecked"
            :name="item.id"
            @change="e => checkboxChange(e, item)"
          >
            <div class="option_item">
              {{ item.trueName }}
            </div>
          </u-checkbox>
        </u-checkbox-group>
      </div>
    </div>

    <div
      :class="{
        mybtn: 1,
        normal: 1,
        fixedBottom: 1,
        loading: loading,
        disabled: loading
      }"
      @click="confirmDialogShow = true"
    >
      提交
    </div>

    <u-modal
      v-model="confirmDialogShow"
      content="确认提交"
      show-cancel-button
      @confirm="submit"
    />
  </div>
</template>

<script>
import {
  getUserPage,
  submitModel,
  getKeyByModelId,
  handleNodeFreeSelectUser
} from '@/api/commonlist';
import WPicker from '@/components/w-picker/w-picker';
import _ from 'lodash';

import { createNamespacedHelpers } from 'vuex';

import { Message } from '@/utils/utils';
import { upFileMulti } from '@/utils/files.js';
import { uploadFilesArr, isPromise } from '@/pages/statistic/commonMethods.js';

const { mapState } = createNamespacedHelpers('formModule');

export default {
  name: 'CommonViewSp',

  components: {
    WPicker
  },

  data() {
    return {
      pickerValue: [],
      timePickvisible: false,
      isOpenTimeRange: false,
      isSp: '',
      users: [],
      select: [], // 选中de用户
      toggleSelect: false,
      renderData: [],
      loading: false,
      confirmDialogShow: false,
      searchUser: '',

      userNodeQuery: {}, // 存放handleNodeFreeSelectUser数据
      bpmParams: {},
      userNode: ''
    };
  },

  computed: {
    filteredUser() {
      return this.users.filter(u => u.trueName.includes(this.searchUser));
    },

    ...mapState({
      stateDetailRenderList: state => state.listDetailRenderData,
      stateBusinessFields: state => state.businessFields,
      componentType: state => state.componentType
    })
  },

  created() {
    this.isSp = this.$route.params.isSp;
    this.init();
  },

  methods: {
    timeStatucChange(v) {
    },

    pickTimer({ value }) {
      this.pickerValue = value;
    },

    init() {
      // const renderData = getLocalStorage('listDetailRenderData');
      const renderData = _.cloneDeep(this.stateDetailRenderList);
      let flag = true;

      if (renderData && renderData.length) {
        this.renderData = renderData;
      } else {
        // 没有取到需要提交数据
        Message('数据丢失');
        flag = false;
        setTimeout(() => {
          this.$router.replace('/');
        }, 1000);
      }

      if (flag) {
        if (this.isSp === '1') {
          this.getUsersWithProcess();
        } else {
          this.getUsersWithNoProcess();
        }
      }
    },

    // 走流程时候用户数据
    async getUsersWithProcess() {
      const {
        params: {
          listId: modelId
        }
      } = this.$route;

      const { success, data: bpmParams } = await getKeyByModelId({ modelId });
      if (success) {
        const {
          id: defId
          // key: defKey
        } = bpmParams;

        this.bpmParams = bpmParams;

        const requestData = {
          action: 'start',
          businessKey: '',
          data: {},
          defId,
          extendConf: { nodeId: '' },
          instanceId: '',
          nodeId: ''

        };

        handleNodeFreeSelectUser(requestData).then(res => {
          const {
            success,
            data
          } = res;

          if (success) {
            this.userNodeQuery = data;
            const {
              nodeIdentitysMap
            } = data;

            const nodeIdentKeys = Object.keys(nodeIdentitysMap);
            if (nodeIdentKeys.length !== 1) {
              Message('bpm流程节点只能存在一个');
            } else {
              const key = nodeIdentKeys[0];
              const users = nodeIdentitysMap[key];

              users.forEach(item => {
                item.trueName = item.name;
                if (this.select.includes(item.id)) {
                  item.myChecked = true;
                } else {
                  item.myChecked = false;
                }
              });

              this.toggleSelect = this.select.length === data.length && data.length || false;

              this.userNode = key;
              this.users = users;
            }
          }
        });
      }
    },

    // 不走流程用户获取
    getUsersWithNoProcess() {
      getUserPage({
        pageType: 0
      }).then(res => {
        if (res.success) {
          const data = res.data;
          data.forEach(item => {
            if (this.select.includes(item.id)) {
              item.myChecked = true;
            } else {
              item.myChecked = false;
            }

            this.toggleSelect = this.select.length === data.length && data.length || false;
          });
          this.users = data;
        }
      });
    },

    checkboxGroupChange(select) {
      const len = select.length;
      this.select = select;
      this.toggleSelect = len && len === this.users.length || false;
    },

    checkboxChange({ value }, item) {
      item.myChecked = value;
      this.$set(item, 'myChecked', value);
      this.$forceUpdate();
    },

    checkboxAll({ value }) {
      if (value) {
        this.select = this.users.map(u => u.id);
      } else {
        this.select = [];
      }

      this.syncSelEct();
    },

    syncSelEct() {
      this.users.forEach(u => {
        u.myChecked = this.select.includes(u.id);
      });
    },

    // 上传文件
    uploadFiles(files, guid) {
      const form = new FormData();
      form.append('guid', guid);
      files.map(file => {
        form.append('files', file);
      });
      return upFileMulti(form);
    },

    submit() {
      const {
        stateDetailRenderList,
        stateBusinessFields,
        componentType
      } = this;

      const renderData = _.cloneDeep(stateDetailRenderList);
      const templateBusinessFields = _.cloneDeep(stateBusinessFields);
      const fileTypes = Object.values(componentType);

      let needUploadFiles = false;

      const {
        listId: modelId,
        tableId
      } = this.$route.params;
      const toUsers = this.select;

      if (!toUsers.length) {
        Message('请至少选中一名用户');
        return;
      }

      const requestData = {
        modelId,
        toUsers,
        businessFields: templateBusinessFields.map(o => ({
          ...o,
          value: o.myValue
        })),
        bodyData: [
          {
            tableId,
            data: [
              renderData.reduce((p, c) => {
                if (fileTypes.includes(c.componentType)) {
                  needUploadFiles = true;
                } else {
                  p[c.dataIndex] = c.myValue;
                }

                return p;
              }, {})
            ]
          }
        ]
      };

      if (this.isOpenTimeRange) {
        const timers = this.pickerValue;
        if (timers.length) {
          requestData.startTime = timers[0];
          requestData.endTime = timers[1];
        } else {
          Message('请选择时间范围');
          return;
        }
      }

      if (this.isSp === '1') {
        const {
          userNode,
          bpmParams
        } = this;

        const {
          id: defId,
          key: defKey,
          sId
        } = bpmParams;

        const bpmBody = {
          defId,
          defKey,
          sId,
          action: 'start',
          opinion: '发起',
          extendConf: { nodeId: '' },
          destination: userNode,
          nodeUsers: {
            [userNode]: ''
          }
        };

        requestData.bpmBody = bpmBody;
      }

      this.loading = true;

      submitModel(requestData).then(res => {
        const message = res.message;
        if (res.success) {
          // 有文件待上传
          if (needUploadFiles) {
            const filesItem = stateDetailRenderList.filter(item => item.componentType === componentType.chooseFile);
            const imgsItem = stateDetailRenderList.filter(item => item.componentType === componentType.chooseImage);

            const waitPrimise = uploadFilesArr({
              filesItem,
              imgsItem,
              guid: res.data[0].acceptance_form_num
            });

            if (isPromise(waitPrimise)) {
              waitPrimise.then(() => {
                this.submitAfter(message);
              });
            } else {
              this.submitAfter(message);
            }
          } else {
            this.submitAfter(message);
          }
        } else {
          this.submitAfter(message, false);
        }
      });
    },

    submitAfter(message, type = true) {
      Message(message);
      setTimeout(() => {
        this.loading = false;
        if (type) {
          this.$router.replace('/list?title=模板库&url=aaa%2Fbbb');
        }
      }, 500);
    }

  }
};
</script>

<style lang="scss" scoped>
.listDetailSp {
  width: 100%;
  height: calc(100% - 20px);
  top: 20px;
  position: relative;
  // margin-top: 20px;
  // overflow: hidden;

  .header {
    margin-bottom: 10px;
    font-size: 15px;
    min-height: 110px;
    .cell {
      -webkit-box-orient: horizontal;
      -webkit-box-direction: normal;
      -webkit-flex-direction: row;
      flex-direction: row;
      -webkit-box-align: center;
      -webkit-align-items: center;
      align-items: center;
      position: relative;
      box-sizing: border-box;
      width: 100%;
      padding: 14px 12px;
      color: #606266;
      background-color: #fff;
      text-align: left;
      align-items: center;
      display: flex;
      justify-content: space-between;
      position: relative;

      &::before,
      &::after
      {
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        height: .5px;
        background-color: #E4E4E4;
      }

      &::after {
        bottom: 0;
      }

      &::before {
        top: 0;
      }

      .cell-right {
        display: flex;
        align-items: center;
      }
    }

    .speedTimePickOut {
      animation-duration: .6s;
    }
  }

  .listDetailSp_container {
    margin-left: 12px;
    width: calc(100% - 24px);
    height: 400px;
    position: relative;
    z-index: 2;

    .usrs_header {
      display: flex;
      align-items: center;
    }

    .userSelect_container {
      padding: 10px 24px;
      padding-right: 0;
      width: calc(100% - 24px);
      height: 100%;

      overflow-x: hidden;
      overflow-y: auto;

      background-color: #fff;
      .option_item {
        // background-color: red;
        width: 100%;
      }
    }

    &::after {
      content: '';
      display: block;
      position: absolute;
      z-index: 1;
      pointer-events: none;
      border-radius: 4px;

      top: -15px;
      bottom: -70px;
      left: -5px;
      right: -5px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }

  .fixedBottom {
     position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
  }

}

/deep/ .u-checkbox {
  .u-checkbox__label {
    width: 100%;
  }
  margin-bottom: 10px;
}
</style>
